<template>
  <!-- 权限分配弹窗 -->
  <a-modal
    v-model:open="permModalVisible"
    title="分配权限"
    width="700px"
    @ok="handlePermissionSubmit"
    @cancel="permModalVisible = false"
    :confirm-loading="permSubmitLoading"
  >
    <a-spin :spinning="permLoading">
      <div v-if="permissionTree.length > 0">
        <a-tree
          v-model:checkedKeys="checkedPermissions"
          :tree-data="permissionTree"
          checkable
          :defaultExpandAll="true"
          :autoExpandParent="true"
        />
      </div>
      <div v-else>
        <a-empty description="暂无权限数据" />
      </div>
    </a-spin>
  </a-modal>
</template>
<script setup>
import { getPermissionList, getPermissionsByRoleId } from '@/request/api';
const permModalVisible = ref(false);
const permLoading = ref(false);
const permSubmitLoading = ref(false);
const checkedPermissions = ref([]);
const permissionTree = ref([]);
const permissionList = ref([]);
const currentRoleId = ref(null);
const props = defineProps({

});
// 加载权限列表
const loadPermissionList = async () => {
  try {
    const res = await getPermissionList();
    console.log('权限列表:', res);
    if (res.code === 200 && res.data) {
      permissionList.value = res.data;
      // 构建权限树形结构
      permissionTree.value = buildPermissionTree(res.data);
      console.log('构建的权限树:', permissionTree.value);
    } else {
      message.error(res?.message || '获取权限列表失败');
    }
  } catch (error) {
    console.error('加载权限列表出错:', error);
    message.error('加载权限列表失败');
  }
};
// 打开权限分配模态框
const handlePermission = async (record) => {
  console.log('准备加载角色权限，角色ID:', record.id);
  currentRoleId.value = record.id;
  permModalVisible.value = true;
  checkedPermissions.value = [];
  
  // 加载角色已有的权限
  permLoading.value = true;

  try {
    // 确保传递的是对象格式
    console.log('调用API前');
    const params = { roleId: record.id };
    console.log('API参数:', params);
    const res = await getPermissionsByRoleId(params);
    console.log('API响应:', res);
    
    if (res && res.code === 200 && res.data) {
      checkedPermissions.value = res.data.map(p => p.id?.toString() || p.toString());
      console.log('权限IDs:', checkedPermissions.value);
      
      // 确保权限树已加载
      if (permissionTree.value.length === 0) {
        await loadPermissionList();
      }
    } else {
      message.error(res?.message || '获取角色权限失败');
    }
  } catch (error) {
    console.error('加载角色权限出错:', error);
    message.error('加载角色权限失败');
  } finally {
    permLoading.value = false;
  }
};
// 构建权限树形结构
const buildPermissionTree = (permissionList) => {
  // 将菜单数据转换为树形结构
  const buildMenuTree = (menus, parentId = 0) => {
    return menus
      .filter((menu) => menu.parent_id === parentId)
      .map((menu) => {
        // 获取当前菜单的子菜单
        const children = buildMenuTree(menus, menu.id);
        
        // 创建当前节点
        const node = {
          title: menu.title,
          key: menu.id.toString(),
          type: menu.type,
          permission_code: menu.permission_code,
          selectable: menu.type !== 'menu' || !children.length
        };
        
        // 只有存在子节点时才添加children属性
        if (children.length > 0) {
          node.children = children;
        }
        
        return node;
      });
  };
  
  return buildMenuTree(permissionList);
};
const handlePermissionSubmit = () => {
  console.log('checkedPermissions', checkedPermissions.value);
};
onMounted(() => {  

});
defineExpose({
  handlePermission
});
</script>


